<?php

namespace app\admin\controller\general;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 附件管理
 *
 * @icon   fa fa-circle-o
 * @remark 主要用于管理上传到又拍云的数据或上传至本服务的上传数据
 */
class Attachment extends Backend
{

    /**
     * @var \app\common\model\Attachment
     */
    protected $model = null;
    protected $categorylist = [];
    protected $relationSearch = true; //开启关联查询 否则会提示 id 未声明

    public function _initialize()
    {
        parent::_initialize();

        $this->modelcate = model('app\common\model\Category');

        $tree = Tree::instance();
        $tree->init(collection($this->modelcate->where("id !=17 && id !=18")->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }


        $this->view->assign("parentList", $categorydata);




        $this->model = model('Attachment');
        $this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $mimetypeQuery = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['mimetype']) && preg_match("/[]\,|\*]/", $filterArr['mimetype'])) {
                $this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['mimetype' => '']))]);
                $mimetypeQuery = function ($query) use ($filterArr) {
                    $mimetypeArr = explode(',', $filterArr['mimetype']);
                    foreach ($mimetypeArr as $index => $item) {
                        if (stripos($item, "/*") !== false) {
                            $query->whereOr('mimetype', 'like', str_replace("/*", "/", $item) . '%');
                        } else {
                            $query->whereOr('mimetype', 'like', '%' . $item . '%');
                        }
                    }
                };
            }

            //快速搜索 根据 id title 搜索
            list($where, $sort, $order, $offset, $limit) = $this->buildparams("id,title,choice.name");
            $total = $this->model
                ->with(['choice'])
                ->where($mimetypeQuery)
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['choice'])
                ->where($mimetypeQuery)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            foreach ($list as $k => &$v) {
                $v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : $this->view->config['upload']['cdnurl']) . $v['url'];
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 选择附件
     */
    public function select()
    {
        if ($this->request->isAjax()) {
            return $this->index();
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");


            if ($params) {

                if($params["url"]){
                    //获取文件后缀
                    $ext = explode(".",$params["url"])[1];

                    if(!in_array($ext,["doc","docx","xls","xlsx","pdf","ppt","pptx","pdf"])){
                        $this->error("文件格式不合法");
                    }
                    $params["imagetype"] = $ext;
                }else{
                    $params["imagetype"] = "";

                }


                $params = $this->preExcludeFields($params);



                try {

                    $params['content'] = str_replace('src="/uploads',"src=\"http://".$_SERVER['HTTP_HOST']."/uploads",$params['content']);

                    $result = $this->model->where("id=$ids")->update($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isAjax()) {

            $params = $this->request->post();

            if ($params) {

                if($params["row"]["url"]){
                    //获取文件后缀
                    $ext = explode(".",$params["row"]["url"])[1];

                    if(!in_array($ext,["doc","docx","xls","xlsx","pdf","ppt","pptx","pdf"])){
                        $this->error("文件格式不合法");
                    }
                    $params["row"]["imagetype"] = $ext;
                }



                   $params["row"]['content'] = str_replace('src="/uploads',"src=\"http://".$_SERVER['HTTP_HOST']."/uploads",$params["row"]['content']);



                try {
                    $res = $this->model->insertGetId($params["row"]);

                    if($res){
                        $this->success("添加成功");
                    }
                } catch (ValidateException $e) {
                    $this->error($e->getMessage());
                }
            }

            $this->error("添加失败");
        }
        return $this->view->fetch();
    }

    /**
     * 删除附件
     * @param array $ids
     */
    public function del($ids = "")
    {

        $collect = model("collect");

        $collect->where("aid",'in',$ids)->delete();

        if ($ids) {
            \think\Hook::add('upload_delete', function ($params) {
                $attachmentFile = ROOT_PATH . '/public' . $params['url'];
                if (is_file($attachmentFile)) {
                    @unlink($attachmentFile);
                }
            });
            $attachmentlist = $this->model->where('id', 'in', $ids)->select();
            foreach ($attachmentlist as $attachment) {
                \think\Hook::listen("upload_delete", $attachment);
                $attachment->delete();
            }

            //删除收藏表对应数据

            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
